package com.hbsx.why.ui.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.hbsx.why.NormalMainActivity;
import com.hbsx.why.R;
import com.hbsx.why.TabMainActivity;
import com.hbsx.why.adapter.LGRecycleViewAdapter;
import com.hbsx.why.adapter.LGViewHolder;
import com.hbsx.why.base.BaseApplication;
import com.hbsx.why.base.BaseFragment;
import com.hbsx.why.ui.act.HomeSearchActivity;
import com.hbsx.why.ui.activity.ActivityActivity;
import com.hbsx.why.ui.activity.ActivityDetailActivity;
import com.hbsx.why.ui.mall.MallActivity;
import com.hbsx.why.utils.LogUtils;
import com.hbsx.why.utils.PermissionUtils;
import com.hbsx.why.utils.PopWindow;
import com.hbsx.why.utils.RecyclerViewUtils;
import com.hbsx.why.utils.cache.GlideUtil;
import com.hbsx.why.utils.refresh.PullScrollView;
import com.hbsx.why.utils.refresh.PullToRefreshLayout;
import com.hbsx.why.utils.refresh.RefreshUtil;
import com.hbsx.why.utils.refresh.listener.ScrollViewListener;
import com.hbsx.why.views.SpacesItemDecoration;
import com.jock.cityselecter.CitySelecterActivity;
import com.squareup.leakcanary.RefWatcher;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomeFragment extends BaseFragment {
    public static TabMainActivity myTabActivity;
    private static String mTitle;
    private static String BUNDLE_flag = "BUNDLE_flag";
    @BindView(R.id.top_linear)
    LinearLayout top_linear;
    @BindView(R.id.home_PullScrollView)
    PullScrollView scrollView;
    @BindView(R.id.home_PullToRefreshLayout)
    PullToRefreshLayout homePullToRefreshLayout;
    @BindView(R.id.rv_list_1)
    RecyclerView rvList1;
    @BindView(R.id.rv_list_2)
    RecyclerView rvList2;
    @BindView(R.id.home_dq)
    TextView homeDq;
    @BindView(R.id.home_sys)
    TextView homeSys;
    @BindView(R.id.home_viewPager)
    ViewPager homeViewPager;
    @BindView(R.id.home_viewpage_icon1)
    ImageView homeViewpageIcon1;
    @BindView(R.id.home_viewpage_icon2)
    ImageView homeViewpageIcon2;
    @BindView(R.id.home_activitycalender)
    LinearLayout homeActivitycalender;
    @BindView(R.id.home_search)
    RelativeLayout homeSearch;
    @BindView(R.id.home_dkx_click)
    LinearLayout homeDkxClick;
    @BindView(R.id.banner_viewpage)
    ConvenientBanner convenientBanner;
    @BindView(R.id.marquee_view)
    ViewFlipper marqueeView;
    private ArrayList<View> mViewList = new ArrayList<View>();
    private MeunAdd meunAdd;
    private MenuAdd1 meunAdd1;
    private int flag;
    public static NormalMainActivity myNormalMainActivity;

    private HomeAdapter homeAdapter;
    private Context context;
    List<Integer> integerList;
    private int banner_height = 400;

    @Override
    protected int getLayout() {
        return R.layout.home_frament_main;
    }

    @Override
    protected void onInit() {
        context = getActivity();

        integerList = new ArrayList<>();
        integerList.add(R.mipmap.banner_icon_new1);
        integerList.add(R.mipmap.banner_icon_new2);
        integerList.add(R.mipmap.banner_icon_new3);

        /**
         * 头部轮播图片
         */
        if (convenientBanner != null) {
            //开始自动翻页
            convenientBanner.startTurning(3000);
            convenientBanner.setPageTransformer(new ViewPager.PageTransformer() {
                @Override
                public void transformPage(View page, float position) {
                }
            });
            convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                @Override
                public NetworkImageHolderView createHolder() {
                    return new NetworkImageHolderView();
                }

            }, integerList).setPageIndicator(new int[]{R.mipmap.point_no, R.mipmap.point_sel})
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
            convenientBanner.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                }
            });
        }

//        initPopWindow(top_linear);
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getContext());
        homeViewPager.setAdapter(myPagerAdapter);
        Bundle arguments = getArguments();
        if (arguments != null) {
            flag = arguments.getInt(BUNDLE_flag);
        }
        RefreshUtil.changeRefreshLableImg(homePullToRefreshLayout);
        scrollView.setPullDownEnable(true);
        scrollView.setPullUpEnable(true);
        top_linear.getBackground().setAlpha(0);
        scrollView.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(PullScrollView scrollView, int x, int y, int oldx, int oldy) {
                if (y <= 0) { // 设置标题的背景颜色
                    top_linear.getBackground().setAlpha(0);
                    //top_linear.setBackgroundColor(getBgColor(0));
                } else if (y > 0 && y <= banner_height) { // 滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                    float scale = (float) y / banner_height;
                    float alpha = (255 * scale);
                    top_linear.getBackground().setAlpha((int) alpha);
                    //top_linear.setBackgroundColor(getBgColor((int) alpha));

                } else { // 滑动到banner下面设置普通颜色
                    top_linear.getBackground().setAlpha(255);
                    //top_linear.setBackgroundColor(getBgColor(255));
                }
            }
        });
        homePullToRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                pullToRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        homePullToRefreshLayout.refreshFinish(true);
                        showToast("刷新成功");
                    }
                }, 1000);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                pullToRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        homePullToRefreshLayout.loadMoreFinish(true);
                        showToast("load成功");
                    }
                }, 100);
            }
        });
        homePullToRefreshLayout.setOnDragStatueListener(new PullToRefreshLayout.OnDragStatueListener() {
            @Override
            public void onDraging() {
                top_linear.setVisibility(View.GONE);
            }

            @Override
            public void onDragfinish() {
                top_linear.setVisibility(View.VISIBLE);
            }
        });


//        CustomDialog.Builder dialogBuild = new CustomDialog.Builder(context);
//        CustomDialog dialog = dialogBuild.create();
//        dialog.setCanceledOnTouchOutside(false);// 点击外部区域关闭
//        dialog.show();

        marqueeView.addView(View.inflate(getActivity(), R.layout.notice_layout_item, null));
        marqueeView.addView(View.inflate(getActivity(), R.layout.notice_layout_item, null));
        marqueeView.addView(View.inflate(getActivity(), R.layout.notice_layout_item, null));

        homeViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    homeViewpageIcon1.setImageResource(R.mipmap.ic_yuan_theme);
                    homeViewpageIcon2.setImageResource(R.mipmap.ic_yuan_gray);
                } else {
                    homeViewpageIcon1.setImageResource(R.mipmap.ic_yuan_gray);
                    homeViewpageIcon2.setImageResource(R.mipmap.ic_yuan_theme);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }


    public int getBgColor(int alpha) {
        return Color.argb(alpha,
                28, 92, 164);
    }

    @Override
    public void fetchData() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            if (i == 0) {
                list.add("合肥市图书馆组织集中收看中国人名解放军90周年大会");
            }
            if (i == 1) {
                list.add("文物科技保护专家来我市检测文博馆展厅温湿度");
            }
            if (i == 2) {
                list.add("“宜城大爱，让爱飞翔”书画助残慈善义卖活动在安庆举行");
            }
        }
        homeAdapter = new HomeAdapter(list);
        //是否可滑动  2
        RecyclerViewUtils.setScrollGridLayout(rvList1, getContext(), 1, false);
        RecyclerViewUtils.setScrollGridLayout(rvList2, getContext(), 1, false);
        rvList1.addItemDecoration(new SpacesItemDecoration(getContext()));
        rvList2.addItemDecoration(new SpacesItemDecoration(getContext()));
        rvList1.setAdapter(homeAdapter);
        rvList2.setAdapter(homeAdapter);
        homeAdapter.setOnItemClickListener(R.id.hd_view, new LGRecycleViewAdapter.ItemClickListener() {
            @Override
            public void onItemClicked(View view, int position) {
                startActivity(new Intent(context, ActivityDetailActivity.class));
            }
        });

        // new Thread(runnable).start();
        //initPopWindow(top_linear);
    }


    private PopWindow popWindow;

    public void initPopWindow(View views) {
        popWindow = new PopWindow(context) {
            @Override
            public int getLayoutManu() {
                return R.layout.layout_pop_home_yuyue;
            }

            @Override
            public void getView(View view) {
                view.findViewById(R.id.pop_btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        launch(ActivityDetailActivity.class);
                        popWindow.dismiss();
                    }
                });
                view.findViewById(R.id.img_dimiss).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popWindow.dismiss();
                    }
                });
            }
        };
//        LogUtils.logi("----" + popWindow);
        popWindow.showAsDropDown(views);
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    public static HomeFragment newInstance(String title, int flag) {
        HomeFragment fragment = new HomeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(BUNDLE_flag, flag);
        mTitle = title;
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @OnClick({R.id.hd_view, R.id.home_dq, R.id.home_activitycalender, R.id.book_linear, R.id.more_book_linear,
            R.id.home_dkx_click, R.id.home_sys, R.id.more_tyt_linear, R.id.home_tyt_click, R.id.more_daka_linear,
            R.id.main_renqi_linear, R.id.main_wenchuang_linear, R.id.main_wenhua_linear, R.id.home_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.home_dq:
                getContext().startActivity(new Intent(getContext(), CitySelecterActivity.class));
                break;
            case R.id.hd_view:
                launch(ActivityDetailActivity.class);
                break;
            case R.id.relayout:
                break;
            case R.id.home_activitycalender:
                launch(ActivityCalendar.class);
                break;
            case R.id.main_renqi_linear:
                Intent intent1 = getContext().getPackageManager().getLaunchIntentForPackage("com.first.ahlib");
                if (intent1 != null) {
                    // 这里跟Activity传递参数一样的嘛，不要担心怎么传递参数，还有接收参数也是跟Activity和Activity传参数一样
                    startActivity(intent1);
                } else {
                    // 未安装应用
                    showToast("您的手机没有安装安图视频App");
                }
//                launch(SpaceActivity.class);
                break;
            case R.id.main_wenchuang_linear:
                launch(MallActivity.class);
                break;
            case R.id.main_wenhua_linear:
                launch(GroupsActivity.class);
                break;
            case R.id.home_search:
                launch(HomeSearchActivity.class);
                break;
            case R.id.book_linear:
                launch(BookDtailActivity.class);
                break;
            case R.id.home_dkx_click:
                launch(HomeDKXActivity.class);
                break;
            case R.id.home_tyt_click:
                launch(MusicDtailActivity.class);
                break;
            case R.id.more_tyt_linear:
                launch(MusicDtailActivity.class);
                break;
            case R.id.home_sys:
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                    PermissionUtils.requestPermission(getActivity(), PermissionUtils.CODE_CAMERA, new PermissionUtils.PermissionGrant() {
                        @Override
                        public void onPermissionGranted(int requestCode) {
                            LogUtils.loge("------requestCode----->" + requestCode);

                        }
                    });
                } else {
                    Intent intent = new Intent(context, CaptureActivity.class);
                    startActivityForResult(intent, 200);

                }

                break;
            case R.id.per_pager1_sh:
                launch(ActivityActivity.class);
                //TabMainActivity.setTab(3);
//                startActivity(new Intent(context, ShengHuoActivity.class).putExtra("title","活动"));
                break;
            case R.id.per_pager1_ly:
                startActivity(new Intent(context, QuYiActivity.class).putExtra("title", "院线演出"));
                break;
            case R.id.per_pager1_wy:
                startActivity(new Intent(context, WenYiActivity.class).putExtra("title", "展览"));
                break;
            case R.id.per_pager1_shuh:

                Intent intent2 = getContext().getPackageManager().getLaunchIntentForPackage("com.taoxue");
                if (intent2 != null) {
                    // 这里跟Activity传递参数一样的嘛，不要担心怎么传递参数，还有接收参数也是跟Activity和Activity传参数一样
                    startActivity(intent2);
                } else {
                    // 未安装应用
                    showToast("您手机的没有安装读联体");
                }
//                startActivity(new Intent(context, JiaoYuActivity.class).putExtra("title", "经典阅读"));
                break;
            case R.id.per_pager1_tc:
                startActivity(new Intent(context, ShengHuoActivity.class).putExtra("title", "数字资源"));
                break;
            case R.id.per_pager6_sh:

                startActivity(new Intent(context, WenYiActivity.class).putExtra("title", "非遗"));
                break;
            case R.id.per_pager7_ly:
                startActivity(new Intent(context, TravelActivity.class).putExtra("title", "戏曲"));
                break;
            case R.id.per_pager8_wy:
                startActivity(new Intent(context, ShuHuaActivity.class).putExtra("title", "社团"));
                break;
            case R.id.per_pager9_shuh:
                launch(MallActivity.class);
                //startActivity(new Intent(context, SpaceActivity.class));
                break;
            case R.id.per_pager10_tc:
                launch(AllClassifyActivity.class);
                break;
            case R.id.home_hd_btn:
                launch(ActivityDetailActivity.class);
                break;
            case R.id.home_mfqp:
                launch(ActivityDetailActivity.class);
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                }
            }
        }
    }


    /**
     * 设置viewPager的适配器
     */
    public class MyPagerAdapter extends PagerAdapter {
        private LayoutInflater inflater;

        public MyPagerAdapter(Context context) {
            inflater = LayoutInflater.from(context);
            mViewList.add(inflater.inflate(R.layout.per_pager1, null));
            mViewList.add(inflater.inflate(R.layout.per_pager2, null));
            meunAdd = new MeunAdd(getContext());
            meunAdd1 = new MenuAdd1(getContext());
            meunAdd.initView(mViewList.get(0), "1");
            meunAdd1.initView(mViewList.get(1), "0");
//			initData();
        }

        @Override
        public int getCount() {
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));
            LogUtils.logd("position---->" + position);

            return mViewList.get(position);
        }
    }

    public class HomeAdapter extends LGRecycleViewAdapter<String> {
        public HomeAdapter(List<String> dataList) {
            super(dataList);
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.zxtj_item;
        }

        @Override
        public void convert(LGViewHolder holder, String s, int position) {
            TextView textView = (TextView) holder.getView(R.id.title);
            ImageView imageView = (ImageView) holder.getView(R.id.home_img);
            textView.setText(s);
            if (position == 0) {
                GlideUtil.getInstance().loadLocationImage(context, imageView, R.mipmap.demo_img_changguan);
            }
            if (position == 1) {
                GlideUtil.getInstance().loadLocationImage(context, imageView, R.mipmap.img_space_top1);
            }
            if (position == 2) {
                GlideUtil.getInstance().loadLocationImage(context, imageView, R.mipmap.img_space_top2);
            }
        }
    }

    /**
     * 加载头部轮播图片
     */
    public class NetworkImageHolderView implements Holder<Integer> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, Integer data) {
            //ImageLoaderUtil.displayImage(R.mipmap.banner,imageView);
            //imageView.setBackgroundResource(data);
            //ImageLoaderUtil.displayImage(data.getImg(),imageView);
            Glide.with(context).load(data).into(imageView);
        }
    }
}
